<template>
  <div>
    <el-card>
      <el-form :model="form" size="mini" :rules="rules" label-position="top" ref="form">
        <el-row :gutter="10">
          <el-col :lg="4" :md="6">
            <el-form-item label="机构">
              <select-tree :branch="form.BRANCHNAME" @getBranchName="getBranch">
              </select-tree>
            </el-form-item>
          </el-col>
          <el-col :lg="4" :md="6">
            <el-form-item label="时间" prop="MONTH">
              <el-input v-model.trim="form.MONTH" placeholder="请输入6位年月,如“201910”"></el-input>
            </el-form-item>
          </el-col>
          <el-col :lg="4" :md="6" v-if="info != 'schedule'">
            <el-form-item label="休假类型" prop="ACTIVITYTYPE">
              <el-select v-model="form.ACTIVITYTYPE" placeholder="请选择休假类型">
                <el-option v-for="item in vacationOption" :key="item.ACTIVITYTYPE" :label="item.ACTIVITYTYPENAME"
                  :value="item.ACTIVITYTYPE">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :lg='6' :md='12' :offset="6" class="searchBtnMarginTop">
          
              <el-button type="primary" icon="el-icon-search" size='mini' @click="clickQuery">查询
              </el-button>
              <el-button type="warning" size="mini" icon="el-icon-refresh" @click="resetForm('form')">重置</el-button>

          </el-col>
        </el-row>
        <el-row style="margin-bottom: 20px;">

          <el-col :lg="2" :md="3" style="margin-right: 25px;">
            <el-button type="success" size="mini" icon="el-icon-download" @click="downloadTemplate">导出报表</el-button>
          </el-col>
          <el-col :lg="3" :md="3" v-if="info =='schedule'">
            <el-button type="success" size="mini" icon="el-icon-download" @click="downloadTemplate('detail')">导出人员明细
            </el-button>
          </el-col>
        </el-row>
      </el-form>
      <!-- 人员排班 -->
      <div v-show="info == 'schedule'">
        <el-table :data="tableData" show-summary :summary-method="getSummaries" :span-method="objectSpanMethod" border>
          <el-table-column prop="DATE" label="日期" align="center">
          </el-table-column>
          <el-table-column prop="ACTIVITY" label="活动类型编号" align="center">
            <template slot-scope="scope">
              <div>
                {{scope.row.ACTIVITY.ACTIVITYTYPE}}
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="ACTIVITY" label="活动编号" align="center">
            <template slot-scope="scope">
              <div>
                {{scope.row.ACTIVITY.ACTIVITYID}}
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="ACTIVITY" label="活动名称" align="center">
            <template slot-scope="scope">
              <div>
                {{scope.row.ACTIVITY.ACTIVITYNAME}}
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="ACTIVITY" label="颜色" align="center">
            <template slot-scope="scope">
              <el-tag style="width:25%;border:none;margin-top:3px;" size="small" :color="scope.row.ACTIVITY.CALCOLOUR">
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="ACTIVITY" label="人数" align="center">
            <template slot-scope="scope">
              <div>
                {{scope.row.ACTIVITY.COUNT}}
              </div>
            </template>
          </el-table-column>
          <el-table-column label="合计" align="center">
            <template slot-scope="scope">
              <div>
                {{scope.row.DATE | sumFormat}}
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- 人员休假 -->
      <div v-show="info != 'schedule'">
        <el-table :data="tableData" show-summary :summary-method="getSummaries" :span-method="objectSpanMethod" border>
          <el-table-column prop="DATE" label="班次日期" align="center">
          </el-table-column>
          <el-table-column prop="ACTIVITY" label="休假类型编号" align="center">
            <template slot-scope="scope">
              <div>
                {{scope.row.ACTIVITY.ACTIVITYTYPE}}
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="ACTIVITY" label="休假类型" align="center">
            <template slot-scope="scope">
              <div>
                {{scope.row.ACTIVITY.ACTIVITYTYPENAME}}
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="ACTIVITY" label="颜色" align="center">
            <template slot-scope="scope">
              <el-tag style="width:25%;border:none;margin-top:3px;" size="small" :color="scope.row.ACTIVITY.CALCOLOUR">
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="ACTIVITY" label="人数" align="center">
            <template slot-scope="scope">
              <div>
                {{scope.row.ACTIVITY.TOTALNUM}}
              </div>
            </template>
          </el-table-column>
          <el-table-column label="合计" align="center">
            <template slot-scope="scope">
              <div>
                {{scope.row.DATE | sumFormat}}
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>

    </el-card>
  </div>
</template>

<script>
  let that
  import getGlobalParams from "@/common/utils/getGlobalParams";
  import selectTree from "@/components/selectTree5/";
  import vacation from '@/message/wfm/scheduleDataManage/activityManage/actQuery';
  import query from '@/message/wfm/report/vacation/agentVacationQuery';
  import vacationReport from '@/message/wfm/report/vacation/vacationImport';
  import userImport from '@/message/wfm/report/class/userImport';
  import classReport from '@/message/wfm/report/class/classImport';
  import querySchedule from '@/message/wfm/report/class/querySchedule';
  import request from "@/common/utils/requestWFM";
  let date = new Date
  let year = date.getFullYear()
  let month = date.getMonth() + 1
  month = (month < 10 ? "0" + month : month);
  let defaultDate = (year.toString() + month.toString())
  export default {
    props: {
      info: String
    },
    components: {
      selectTree
    },
    beforeCreate: function () {
      that = this;
    },
    filters: {
      sumFormat: (date) => {
        let sum = 0
        that.tableData.map(item => {
          if (item.DATE == date) {
            sum += that.info == 'schedule' ? item.ACTIVITY.COUNT : item.ACTIVITY.TOTALNUM;
          }
        })
        return sum
      }
    },
    data() {
      return {
        pos: 0,
        spanArr: [],
        tableData: [],
        rules: {
          BRANCHNO: [{
            required: true,
            message: '请选择机构',
            trigger: 'change'
          }],
          MONTH: [{
              required: true,
              message: '请输入年月',
              trigger: 'blur'
            },
            {
              min: 6,
              max: 6,
              message: '长度为6个字符，如“201901”',
              trigger: 'blur'
            }
          ],
        },
        vacationOption: [],
        form: { //表单数据
          BRANCHNO: this.$store.getters.BranchNum,
          BRANCHNAME: this.$store.getters.BranchName,
          ACTIVITYTYPE: '', //休假类型
          MONTH: defaultDate
        },
        fileUrl: getGlobalParams.get("FileDownloadAddress"),
      }
    },
    computed: {

    },
    mounted() {
      // 活动类型大类查询
      this.actQuery();
      this.clickQuery();
    },
    methods: {
      // 查询
      clickQuery() {
        if (this.info == 'schedule') {
          // 排班统计查询
          this.querySchedule();
        } else {
          // 休假统计查询
          this.queryModel();
        }
      },
      // 合计
      getSummaries(param) {
        const {
          columns,
          data
        } = param
        const sums = []
        columns.forEach((column, index) => { //这步是为了让最后一行出现 合计 这一行，并且最后一行第一列出现 合计 二字。合计的字可以在这里更改
          if (index === 0) {
            sums[index] = '合计'
            return
          } else if (index === 4 && this.info != 'schedule') {
            let sum1 = 0
            data.map(item => {
              sum1 += item.ACTIVITY.TOTALNUM
            })
            sums[index] = sum1
          } else if (index === 5 && this.info == 'schedule') {
            let sum1 = 0
            data.map(item => {
              sum1 += Number(item.ACTIVITY.COUNT)
            })
            sums[index] = sum1
          }
        })
        return sums;
        // console.log(data)
      },
      // 活动类型查询
      async actQuery() {
        let resBody = new vacation()
        resBody.data.ACTIVITYTYPE = '';
        resBody.data.ACTIVITYTYPENAME = '';
        resBody.data.ACTIVITYCATEG = '04';
        resBody.data.CurrPage = '1';
        resBody.data.PageRowNum = '100';
        let response = await request(resBody);
        if (response.SYS_HEAD.ReturnCode == "000000") {
          this.vacationOption = response.BODY.RSPSTRUCT;
        } else {
          this.$message({
            type: "error",
            message: "请求失败，错误码:" + response.SYS_HEAD.ReturnCode + "，错误信息：" + response.SYS_HEAD.ReturnMessage
          })
        }
      },
      resetForm(formName) {
        this.$refs[formName].resetFields();
      },
      getSpanArr(data) {
        for (var i = 0; i < data.length; i++) {
          if (i === 0) {
            this.spanArr.push(1);
            this.pos = 0
          } else {
            // 判断当前元素与上一个元素是否相同
            if (data[i].DATE === data[i - 1].DATE) {
              this.spanArr[this.pos] += 1;
              this.spanArr.push(0);
            } else {
              this.spanArr.push(1);
              this.pos = i;
            }
          }
        }
      },
      // 合并单元格
      objectSpanMethod({
        row,
        column,
        rowIndex,
        columnIndex
      }) {
        if (columnIndex === 0 || columnIndex === 5 && this.info !== 'schedule') {
          const _row = this.spanArr[rowIndex];
          const _col = _row > 0 ? 1 : 0;
          return {
            rowspan: _row,
            colspan: _col
          }
        } else if (columnIndex === 0 || columnIndex === 6 && this.info === 'schedule') {
          const _row = this.spanArr[rowIndex];
          const _col = _row > 0 ? 1 : 0;
          return {
            rowspan: _row,
            colspan: _col
          }
        }
      },
      // 导出班表
      async downloadTemplate(data) {
        let resBody
        if (data == 'detail') {
          resBody = new userImport()
        } else {
          if (this.info != 'schedule') {
            resBody = new vacationReport()
            resBody.data.ACTIVITYTYPE = this.form.ACTIVITYTYPE
          } else {
            resBody = new classReport()
          }
        }
        resBody.data.MONTH = this.form.MONTH;
        resBody.data.BRANCHNO = this.form.BRANCHNO
        let response = await request(resBody);
        if (response.SYS_HEAD.ReturnCode == "000000") {
          let res = response.BODY
          let name = res.FileName
          let url = res.FilePath
          this.downloadFile(this.fileUrl + url + '/' + name)
          console.log(response)
        } else {
          this.$message({
            type: "error",
            message: "请求失败，错误码:" + response.SYS_HEAD.ReturnCode + "，错误信息：" + response.SYS_HEAD.ReturnMessage
          })
        }
      },
      getBranch(data) {
        // 机构变化重新赋值
        this.form.BRANCHNO = data.BRANCHNO;
        this.form.BRANCHNAME = data.BRANCHNAME;
      },
      // 查询休假统计
      queryModel() {
        this.$refs['form'].validate(async (valid) => {
          if (valid) {
            let resBody = new query();
            resBody.data.MONTH = this.form.MONTH;
            resBody.data.ACTIVITYTYPE = this.form.ACTIVITYTYPE
            resBody.data.BRANCHNO = this.form.BRANCHNO
            let response = await request(resBody);
            if (response.SYS_HEAD.ReturnCode == "000000") {
              // console.log(response.BODY)
              let data = response.BODY.RSPSTRUCT
              let testData = []
              data.forEach(item => {
                if (item.ACTIVITY.length > 0) {
                  testData.push(item)
                }
              });
              let table = []
              testData.forEach(item => {
                item.ACTIVITY.forEach(element => {
                  table.push({
                    'DATE': item.DATE,
                    'ACTIVITY': element
                  })
                })
              })
              this.spanArr = []
              this.tableData = table
              this.getSpanArr(table)
            } else {
              this.$message({
                type: "error",
                message: "请求失败，错误码:" + response.SYS_HEAD.ReturnCode + "，错误信息：" + response.SYS_HEAD
                  .ReturnMessage
              })
            }
          } else {
            console.log('error submit!!');
            return false;
          }
        });

      },
      // 查询排班统计
      querySchedule() {
        this.$refs['form'].validate(async (valid) => {
          if (valid) {
            let resBody = new querySchedule();
            resBody.data.MONTH = this.form.MONTH;
            resBody.data.BRANCHNO = this.form.BRANCHNO
            let response = await request(resBody);
            if (response.SYS_HEAD.ReturnCode == "000000") {
              // console.log(response.BODY)
              let data = response.BODY.RSPSTRUCT;
              let testData = [];
              let DATE = [];
              data.forEach(item => {
                DATE = [];
                item.DATE.forEach(info => {
                  if (info.ACTIVITYID !== "") {
                    DATE.push(info)
                  }
                })
                if (DATE.length > 0) {
                  testData.push({
                    'DATE': DATE,
                    'CLASSESDATE': item.CLASSESDATE
                  })
                }
              });
              // console.log(testData);
              let table = []
              testData.forEach(item => {
                item.DATE.forEach(element => {
                  table.push({
                    'DATE': item.CLASSESDATE,
                    'ACTIVITY': element
                  })
                })
              })
              this.spanArr = []
              this.tableData = table;
              this.getSpanArr(table)
            } else {
              this.$message({
                type: "error",
                message: "请求失败，错误码:" + response.SYS_HEAD.ReturnCode + "，错误信息：" + response.SYS_HEAD
                  .ReturnMessage
              })
            }
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      },
    }
  }

</script>

<style rel="stylesheet/scss" lang="scss">
  .el-table th.gutter {
    display: table-cell !important;
  }

</style>
